from PySide6.QtCore import Qt, Signal
from qfluentwidgets import SettingCard, FluentIconBase, ComboBox
from app.common.config import cfg

class DropDownSettingCard(SettingCard):
    """ 下拉框设置卡片 """
    
    valueChanged = Signal(str)

    def __init__(self, icon: FluentIconBase, title: str, content: str, 
                 configItem, items=None, parent=None):
        """
        Parameters
        ----------
        icon: FluentIconBase
            卡片图标
        title: str
            卡片标题
        content: str
            卡片内容描述
        configItem: ConfigItem
            配置项
        items: list
            下拉框选项列表
        parent: QWidget
            父组件
        """
        super().__init__(icon, title, content, parent)
        self.configItem = configItem
        
        # 创建下拉框
        self.comboBox = ComboBox(self)
        self.comboBox.setMinimumWidth(200)
        
        # 添加下拉选项
        if items:
            self.comboBox.addItems(items)
            # 设置当前值,如果配置的值在选项中则选中,否则选中第一项
            if self.configItem.value in items:
                self.comboBox.setCurrentText(self.configItem.value)
            elif items:
                self.comboBox.setCurrentText(items[0])
                self.configItem.value = items[0]
                cfg.save()
        
        # 将下拉框添加到右侧
        self.hBoxLayout.addWidget(self.comboBox, 0, Qt.AlignRight)
        self.comboBox.currentTextChanged.connect(self._onValueChanged)

    def _onValueChanged(self, text: str):
        """ 值改变时的处理 """
        self.configItem.value = text
        cfg.save()
        self.valueChanged.emit(text)

    def getValue(self):
        """ 获取当前值 """
        return self.comboBox.currentText()

    def setValue(self, value: str):
        """ 设置值 """
        if value in [self.comboBox.itemText(i) for i in range(self.comboBox.count())]:
            self.comboBox.setCurrentText(value)
        
    def setItems(self, items: list):
        """ 设置下拉选项 """
        currentText = self.comboBox.currentText()
        self.comboBox.clear()
        self.comboBox.addItems(items)
        
        # 尝试保持原来选中的值,如果不存在则选中第一项
        if currentText in items:
            self.comboBox.setCurrentText(currentText)
        elif items:
            self.comboBox.setCurrentText(items[0])
            self.configItem.value = items[0]
            cfg.save() 